<template>
    <div class="chat-list">
        <div class="search-box">
            <el-input v-model="searchText" placeholder="搜索" prefix-icon="el-icon-search" clearable />
        </div>
        <el-scrollbar height="calc(100vh - 60px)">
            <div v-for="chat in filteredChats" :key="chat.id" class="chat-item"
                :class="{ active: chat.id == activeChat }" @click="$emit('select-chat', chat.id)">
                <el-avatar :size="40" :src="chat.avatar" />
                <div class="chat-info">
                    <div class="chat-name">{{ chat.remark || chat.nickname }}</div>
                    <div class="chat-preview">{{ chat.lastMessage }}</div>
                </div>
                <div class="chat-meta">
                    <div class="chat-time">{{ chat.lastTime }}</div>
                    <el-badge v-if="chat.unread > 0" :value="chat.unread" class="badge" />
                </div>
            </div>
        </el-scrollbar>
    </div>
</template>

<script setup>
import { computed, ref } from 'vue'

const props = defineProps({
  chatList: {
    type: Array,
    required: true
  },
  activeChat: {
    type: Number,
    default: null
  }
})

const emit = defineEmits(['select-chat'])

const searchText = ref('')

const filteredChats = computed(() => {
  if (!searchText.value) return props.chatList
  return props.chatList.filter(chat =>
    chat.name.toLowerCase().includes(searchText.value.toLowerCase()) ||
    chat.lastMessage.toLowerCase().includes(searchText.value.toLowerCase())
  )
})
</script>

<style scoped>
.chat-list {
    height: 100%;
}

.search-box {
    padding: 10px;
    border-bottom: 1px solid #e6e6e6;
}

.chat-item {
    display: flex;
    padding: 12px;
    cursor: pointer;
    border-bottom: 1px solid #f5f5f5;
    align-items: center;
}

.chat-item:hover {
    background-color: #f5f5f5;
}

.chat-item.active {
    background-color: #e6e6e6;
}

.chat-info {
    flex: 1;
    margin-left: 10px;
    overflow: hidden;
}

.chat-name {
    font-size: 14px;
    font-weight: bold;
    margin-bottom: 4px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.chat-preview {
    font-size: 12px;
    color: #999;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.chat-meta {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    margin-left: 10px;
}

.chat-time {
    font-size: 12px;
    color: #999;
    margin-bottom: 4px;
}

.badge {
    margin-top: 2px;
}
</style>